home *** CD-ROM | disk | FTP | other *** search
- Path: piglet.cc.utexas.edu!not-for-mail
- From: lucien@ccwf.cc.utexas.edu
- Newsgroups: comp.lang.c++
- Subject: Re: Memory allocation.
- Date: 17 Feb 1996 10:56:00 -0600
- Organization: The University of Texas at Austin
- Message-ID: <4g51b0$bnn@piglet.cc.utexas.edu>
- References: <1996Feb10.161530.26449@wisipc.weizmann.ac.il>
- NNTP-Posting-Host: piglet.cc.utexas.edu
-
- In article <1996Feb10.161530.26449@wisipc.weizmann.ac.il>,
- Kajdan Dimitry <cerlpvk> wrote:
- >I'm a starter so the question may seem stupid.
-
- Not at all. I'm still a beginner to c++, so this was a good exercise
- for me too.
- 8-)
-
- >
- >Would someone explain why this program works?
- >
- >int* func()
- >{
- >
- >
- > int b[10];
- > for(int i=0;i<9;i++)
- > b[i]=i;
- > return b;
- >}
-
- The fact that this particular function works is fortuitous. The problem is
- that it returns a pointer to an array that is declared local to the
- function. When the function returns, b[10] goes out of scope, and the
- memory that was allocated for it is freed. So, the pointer returned by
- func() doesn't point to a valid address anymore.
- (I did not figure this out on my own - I gleaned this from another reply
- to your post, and from a warning given me by my compiler when I compiled
- this. Wish I could claim that i had, though 8-)).
-
- >
- >int main(){
- >
- > int* x= func();
-
- Here, x points to a memory location that no longer belongs to b[10] in
- func().
-
- >
- >The point is that b is allocated on the stack i.e without "new".
-
- Well, when you declare an array as int b[10]; then memory for the array
- is automagically allocated for it. you could also declare a pointer to
- an array of 10 ints like this:
-
- int *b = new int[10];
-
- The scoping issues involved here are different, since new lets you allocate
- memory on one function and then use or free it in another. memory allocated
- with the new operator isn't tied to the lifetime of a function like
- automatic variables such as "int b[10];" are.
-
- So, return b will return a valid pointer if you declare b this way.
-
- Other ways to fix func() are to declare the array globally, or you can
- declare it static. In both cases, the array will 'persist' even after it goes
- out of scope.
-
- Of course, if I'm wrong about any of this, please correct me.
- Thanks!
-
- Lucien S.
-
-